package cn.hbads.support.json.support;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * <b>输入流的序列化器，将其转换为byte[]后用Base64编码</b>
 * <br><br/>可以通过 @JsonSerialize(using = InputStreamSerializer.class)使用
 */
public class InputStreamSerializer extends JsonSerializer<InputStream> {
    @Override
    public void serialize(InputStream value, JsonGenerator gen, SerializerProvider serializers)
            throws IOException {
        // 将 InputStream 转为 Base64
        byte[] bytes = value.readAllBytes();
        String base64 = Base64.getEncoder().encodeToString(bytes);
        gen.writeString(base64);
    }
}